using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MVC.Models;
using MVC.Models.Database;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace MVC.Controllers
{
    // 特性路由
    // [Route("/")]
    // [Route("[controller]/[action]")]
    public class RegisterController : Controller
    {
        // 数据库连接注入
        private readonly LifengContext _context;
        public RegisterController(LifengContext context)
        {
            _context = context;
        }

        // 返回前端页面
        // [Route("/")]
        [Route("/[controller]")]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 用于注册的请求
        /// </summary>
        [HttpPost]
        [Route("/api/users/")]
        public ApiModel RegisterAccount(RegisterAccountRequest request)
        {
            // return Json(request);
            // 1.判断用户名是否存在
            if (_context.Users.Where(u => u.UserName == request.username).Count() > 0){
                return new ApiModel { status="error",data = "用户名已存在,请更换用户名后重试" };
            }
            // 2.判断邮箱是否存在
            if(_context.Users.Where(u => u.UserEmail == request.email).Count() > 0){
                return new ApiModel { status = "error", data = "邮箱已存在,请更换邮箱后重试" };
            };
            // 生成随机数作为用户id
            Random random = new Random();
            // 创建用户模型
            var model = new User
            {
                UserId = random.Next(1, 999),
                UserName = request.username,
                UserPassword = request.password,
                UserEmail = request.email
            };
            // 3.添加用户
            _context.Users.Add(model);
            // 4.保存到数据库
            // 判断是否添加成功
            if (_context.SaveChanges() > 0)
            {
                return new ApiModel { status = "ok", data = "用户添加成功" };
            }
            return new ApiModel { status = "error", data = "用户添加失败" };
        }

        private ApiModel Object(ApiModel apiModel)
        {
            throw new NotImplementedException();
        }
    }


}